package netWorkPrograming.tcp.tcp02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/27
 * 需求2：服务端接收多条消息，客户端发送多条消息
 */
public class ServerDemo {
    public static void main(String[] args) {
        System.out.println("-------------服务端-------------");
        BufferedReader br = null;
        ServerSocket ss = null;
        try {
            ss=new ServerSocket(8888);
            System.out.println("服务端已启动监听端口号：8888");
            Socket socket = ss.accept();
            System.out.println("客户端已成功接入！");
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String s=null;
            while((s=br.readLine())!=null){
                if(s.equals("exit")){
                    break;
                }
                System.out.println(socket.getInetAddress().getHostAddress()+"说："+s);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
